<?php
/**
 * 配置Service
 * Date: 2025/09/10
 */

namespace App\Services\Admin;

use App\Models\ConfigModel;
use App\Services\BaseService;

class ConfigService extends BaseService
{
    /**
     * 配置信息
     * @date 2025/09/22
     * @return \Illuminate\Http\JsonResponse
     */
    public function info()
    {
        return $this->success(ConfigModel::query()->pluck('content', 'key')->toArray());
    }

    /**
     * 配置详情
     * @date 2025/09/11
     * @param string $type 配置类型
     * @return \Illuminate\Http\JsonResponse
     */
    public function detail($type)
    {
        $result = [];
        $keyList = ConfigModel::TYPE_KEYS[$type] ?? [];
        if (!empty($keyList)) {
            $configList = ConfigModel::query()->whereIn('key', $keyList)->pluck('content', 'key')->toArray();
            foreach ($keyList as $keyItem) {
                $result[$keyItem] = $configList[$keyItem] ?? '';
            }
        }
        return $this->success($result);
    }

    /**
     * 配置更新
     * @date 2025/09/11
     * @param array $params 请求参数
     * @return \Illuminate\Http\JsonResponse
     */
    public function update($params)
    {
        $keyList = ConfigModel::TYPE_KEYS[$params['type']] ?? [];
        if (!empty($keyList)) {
            $configList = ConfigModel::query()->whereIn('key', $keyList)->pluck('content', 'key');
            foreach ($keyList as $keyItem) {
                if (!isset($configList[$keyItem])) {
                    ConfigModel::query()->create([
                        'key' => $keyItem,
                        'content' => $params[$keyItem] ?? '',
                    ]);
                } else {
                    ConfigModel::query()->where('key', $keyItem)->update(['content' => $params[$keyItem] ?? '']);
                }
            }
        }
        return $this->success();
    }
}
